<?php
namespace froyo\cherry\Base;



class BaseModule extends BaseObject{
	protected $name;
	protected $controllerDir = 'controllers';

	protected $configdir;
	protected $controller;
	protected $params = [];
	public function init_(){
		$this->name = $this->name?$this->name:substr(strrchr(get_class($this), "\\"), 1); 
		$basedir = $this->getClassDirPath();
		if(file_exists($basedir.'/'.$this->configdir.'/params.php'))
		{
			$this->params = require $basedir.'/'.$this->configdir.'/params.php';
		}
	}


	public function getparam($name,$default='')
	{
		if(isset($this->params[ $name ]))
		{
			return $this->params[ $name ];
		}
		return Cherry::$app->getParam($name,$default);
	}

	public function getControllerDir(){
		return $this->controllerDir;
	}

	public function handler($request,$controllerName,$action){
		$class = get_class($this);
		$namespace = substr($class,0,strrpos( $class,'\\'));
		$controllerClassName = $namespace.'\\'.$this->controllerDir.'\\'.$controllerName;
		if(!class_exists($controllerClassName))
		{
			throw new \Exception("Route Error, Controller ".$controllerName." Not Exist", 1);
		}
		$this->controller = new $controllerClassName(['request'=>$request,'module'=>$this,'app'=>Cherry::$app]);
		$data = null;
		$action = 'action'.str_replace(' ', '', ucwords(str_replace('-',' ',$action)));
		if(is_callable([$this->controller,$action]))
		{
			$this->controller->trigger('ACTION_BEGAIN');
			$data = call_user_func_array([$this->controller,$action],[]);

			$this->trigger('ACTION_END');
		}

		return $data;
	}
}